import {Component, ElementRef, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams, Platform, Navbar, App} from 'ionic-angular';
import {ApiProvider} from "../../providers/api/api";
import {UnitSourceListPage} from "../unit-source-list/unit-source-list";
import {RecordProvider} from "../../providers/record/record";
import {ImgUploadProvider} from "../../providers/img-upload/img-upload";
import {Subject} from "rxjs/Subject";
import {debounceTime, switchMap} from "rxjs/operators";

declare let xunfeiListenSpeaking: any;

/**
 * Generated class for the ExerciseAnswerPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
/*declare let cordova;*/
@IonicPage()
@Component({
  selector: 'page-exercise-answer',
  templateUrl: 'exercise-answer.html',
})
export class ExerciseAnswerPage {
  exerciseType;//习题类型对应数字串 10001,10002……
  exerciseTypeStr="";//习题类型汉字字符串 单选题，多选题……
  exerciseNo;//习题序号
  teacherId;//教师id
  studentId;//学生id
  exerciseId;//习题id
  unitId;//单元id
  classCourseId;//班课id
  classType;//课堂环节
  start_answer;//是否开始答题状态
  exerciseStartTime;//仅课中有效（习题设置开始答题的时间）

  cur_exercise;//当前习题内容对象
  cur_option;//当前习题选项对象
  cur_stuAnswers;//当前学生作答当前习题的答案记录对象

  exercise_name;//当前习题标题内容

  selectOptionId='';//选择类：选择答案序号拼接串
  area_answer='';//文本类：答案内容

  totalTime = 0;
  time = 0;
  flg=0;//是否可答题 0 ：可以

  counterText;//定时器显示内容

  interval;//倒计时定时器

  counterShow=false;//控制倒计时是否显示的（默认不显示，习题内容全部获取完成了才显示）

  excellentAnswerStudent;//最佳答案答题学生
  excellentAnswerStuNo;//最佳答案学生学号
  excellentAnswer;//最佳答案内容
  showExcellent=false;//是否显示最佳答案

  exercise_image;//习题题干图片

  oldAnswerImage=null;//上次作答图片(用于重新上传时移除之前图片而用)
  answerImage=null;//本次作答答案（用于显示答案图片路径而用）
  exerciseImagePath=null;//当前习题图片相对路径（不带项目目录）（用于当只上传图片而没有保存答案时移除服务器无用图片或者提交答案而用）
  isSaveSuccess=false;//提交答案成功与否（false-未成功，true-成功），若成功则不移除之前上传的答案图片，否则移除之前上传的答案图片

  answer_type;//图片作答还是文字作答（0-文字答题 1-图片答题）

  answerImages='';//答案图片拼接字符串（英文逗号分隔）不带文件路径 用于入库
  answerImagesArray;//答案图片数组 不带文件路径 用于入库
  showAnswerImages='';//答案图片拼接字符串（英文逗号分隔）带文件路径 用于页面展示
  showAnswerImagesArray;//答案图片数组 带文件路径 用于页面展示

  maxImageCount=10;//最大图片数量
  canUpload=0;//判断是否能操作上传按钮（当达到最大图片数量时不能） 0可以，1不可以

  initTime; //进入答题时间戳

  @ViewChild(Navbar) navBar: Navbar;
  constructor(public navCtrl: NavController, public navParams: NavParams,public http:ApiProvider,public platform:Platform,public appCtrl:App, public record: RecordProvider,private imgUpload:ImgUploadProvider) {
/*    platform.ready().then()
    {
/!*      cordova.plugins.xunfeiListenSpeaking.startListen(function(data){
        //data即是返回的文字
      },null,true,true);*!/
    }*/
 }

 // timeInterval;

  @ViewChild('text') textarea: ElementRef;

  pressTime = 0;

  pressing = false;
  onPress(event) {
    xunfeiListenSpeaking.startListen(res => {
      this.area_answer = res;
      this.pressing = false;
      this.textarea.nativeElement.value = res;
    },err=>{
      alert(err)
    }, true, true);
  }

  ionViewDidLoad() {
    this.exerciseType=this.navParams.get("exerciseType");
    this.exerciseNo=this.navParams.get("exerciseNo");
    this.teacherId=this.navParams.get("teacherId");
    this.studentId=this.navParams.get("studentId");
    this.exerciseId=this.navParams.get("exerciseId");
    this.unitId=this.navParams.get("unitId");
    this.classCourseId=this.navParams.get("classCourseId");
    this.classType=this.navParams.get("classType");
    this.start_answer=this.navParams.get("start_answer")==1?1:0;
    this.exerciseStartTime=Date.parse(this.navParams.get("start_time"));
    this.answer_type=this.navParams.get("answer_type");

    this.exerciseStartTime=new Date(this.navParams.get("start_time").replace(/-/g,'/')).getTime();
    this.initTime = Date.parse(new Date().toString());
    this.counter();

    this.getErciseTypeStr(this.exerciseType);

    this.getExerciseInfo();

/*    // 请求防抖；//测试
    this.saveAnswerRes = this.saveAnswerSub.pipe(
      debounceTime(2000),
      switchMap(looktime =>
        this.saveAnswerPost(looktime)
      )
    )

    this.saveAnswerRes.subscribe(item=>{
      if(item["Code"]=="00000000")
      {
        this.isSaveSuccess=true;
        clearInterval(this.interval);

        let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
        if (activeNav.canGoBack()) {
          activeNav.pop();
        }
      }
      else
      {
        this.http.showToast(item["Message"],'bottom')
      }
    });*/

  }

  /**
   *页面离开的时候触发：清空定时器
   */
  ionViewDidLeave()
  {
    clearInterval(this.interval);

    if(this.exerciseType=="10004"&&!this.isSaveSuccess)
    {
      //this.clearAnswerImage();
    }
  }

  /**
   * 获取习题类型对应的汉字名称
   * @param type
   */
  getErciseTypeStr(type)
  {
    switch(type)
    {
      //单选：10001，多选：10002，主观：10004，头脑风暴：10006，投票：10009，判断：10008
      case '10001':
        this.exerciseTypeStr="单选题";
        break;
      case '10002':
        this.exerciseTypeStr="多选题";
        break;
      case '10004':
        this.exerciseTypeStr="主观题";
        break;
      case '10006':
        this.exerciseTypeStr="头脑风暴";
        break;
      case '10009':
        this.exerciseTypeStr="投票题";
        break;
      case '10008':
        this.exerciseTypeStr="判断题";
        break;
      default:
        this.exerciseTypeStr="";
    }
  }

  /**
   * 获取习题详情
   */
  getExerciseInfo()
  {
    this.http.post("/exercise/getExercise.do",{teacherId:+this.teacherId,exerciseId:this.exerciseId,classId:this.classCourseId,
      unitId:this.unitId,studentId:this.studentId,classtype:this.classType}).subscribe(item=>{
        if(item["excellentAnswer"]!=null)
        {
          this.excellentAnswerStudent=item["excellentAnswer"]["Real_Name"];
          this.excellentAnswerStuNo=item["excellentAnswer"]["Stu_No"];
          this.excellentAnswer=item["excellentAnswer"]["answer_option"];
          this.showExcellent=true;
        }

        this.counterShow=true;
        console.log(item);
        this.cur_exercise=item["exercise"];
        this.cur_option=item["options"];
        this.cur_stuAnswers=item["stuAnswers"];
        this.exercise_name=item["exercise"]["exercise_name"];

        if(item["exercise"]["exer_image"]!=null&&item["exercise"]["exer_image"]!='')
        {
          this.exercise_image=this.http.filePath+item["exercise"]["exer_image"];
        }
        else
        {
          this.exercise_image=null;
        }

        //之前没有作答记录或者头脑风暴可以继续作答，提交按钮及录音按钮可操作，否则灰显
        if(item["stuAnswers"]==null||this.exerciseType=="10006")
        {
          this.flg = 0;
          this.time = 0;

          //头脑风暴可以作答多次
          if(this.exerciseType=="10006")
          {
            this.flg = 0;
            this.time = -1;
            this.counterText="答题中";
          }
        }
        else
        {
          //有答案,展示之前答案：选择类
          if(this.exerciseType=="10001"||this.exerciseType=="10002"||this.exerciseType=="10008"||this.exerciseType=="10009")
          {
            this.selectOptionId=item["stuAnswers"]["answer_option"];
            //禁用选项点击

          }
          else//有答案,展示之前答案：文本类
          {
            this.area_answer=item["stuAnswers"]["answer_option"];
            //禁用文本输入

            //主观题展示上次作答图片
            if(this.exerciseType=="10004")
            {
              if(item["stuAnswers"]["answer_image"]!=null&&item["stuAnswers"]["answer_image"]!="")
              {
                //this.oldAnswerImage=item["stuAnswers"]["answer_image"];
                //this.answerImage=this.http.filePath+item["stuAnswers"]["answer_image"];
                this.answerImages=item["stuAnswers"]["answer_image"];
                this.answerImagesArray=this.answerImages.split(",");
                let showImgs='';
                for(let i=0;i<this.answerImagesArray.length;i++)
                {
                  if(this.answerImagesArray[i]!='')
                  {
                    showImgs=showImgs+this.showAnswerImages+this.http.filePath+this.answerImagesArray[i]+',';
                  }
                }
                this.showAnswerImages=showImgs;
                this.showAnswerImagesArray=this.showAnswerImages.split(',');
              }
            }
          }

          this.flg = 1;
          this.time = -1;
          //禁用相关控件
          this.counterText="已提交";
        }

        if(item["exercise"]["start_answer"]=="2")
        {
          this.flg = 1;//与源代码相比自己添加的
          this.time = -1;
          this.counterText="已结束";
        }

      // 计时开始
      if(this.time>=0){
        let now_time = Date.parse(new Date().toString());
        if(this.exerciseStartTime != null){
          now_time = now_time - this.exerciseStartTime;
        }

        this.time = (parseInt(item["exercise"]["answer_time"]) * 60 * 1000 - now_time) / 1000;
        this.totalTime = parseInt(item["exercise"]["answer_time"]) * 60;
        this.counter();
        this.interval = setInterval(() => {
          this.counter();
        }, 1000);
      }
    });
  }

  /**
   * 录音
   * @constructor
   */
  Recording()
  {
    console.log("进入录音");
    //cordova.plugins
/*    this.platform.ready().then()
    {
/!*      cordova.plugins.xunfeiListenSpeaking.startListen(function(data){
        //data即是返回的文字
      },null,true,true);*!/
    }*/
  }


  saveAnswerSub = new Subject();
  saveAnswerRes;
  /**
   * 提交答案
   */
  saveAnswer()
  {
    if(this.flg==1)
      return;
    if(this.isVaild())
    {
      //提交
      let looktime=0;
      if(this.classType=="60002")
      {

      }
      else
      {
        let nowtime=Date.parse(new Date().toString());
        looktime=(nowtime-this.initTime)/1000;
      }
      this.saveAnswerSub.next(looktime);

      this.http.post('/exercise/saveScore.do',{
        teacherId:+this.teacherId,
        exerciseId:this.exerciseId,
        studentId:this.studentId,
        unitId:this.unitId,
        classId:this.classCourseId,
        answer:(this.exerciseType=="10004"||this.exerciseType=="10006")?(((this.answer_type==0&&this.exerciseType=="10004")||this.exerciseType=="10006")?this.area_answer:null):this.selectOptionId,
        lookTime:looktime,
        classtype:this.classType,
        answer_image:this.answer_type==1?this.answerImages:null//this.exerciseImagePath
      }).subscribe(item=>{
        if(item["Code"]=="00000000")
        {
          this.isSaveSuccess=true;
          clearInterval(this.interval);

          let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
          if (activeNav.canGoBack()) {
            activeNav.pop();
          }
        }
        else
        {
          this.http.showToast(item["Message"],'bottom')
        }
      });
    }
  }

  /**
   * 选择类题目点击选项(splice为啥不好使，待学习)
   * @param e
   */
  select(sort,exerciseType)
  {
    if(this.flg==1)
      return;

    console.log("进入选择！");

    let newoption=[];
    if(exerciseType=='10001'||exerciseType=='10009'||exerciseType=='10008')
    {
      this.selectOptionId=sort;
    }
    else if(exerciseType=='10002')
    {
      if(this.selectOptionId.indexOf(sort)>=0)
      {
        let index=this.selectOptionId.split(',').indexOf(sort);
        for(let i=0;i<this.selectOptionId.split(',').length;i++)
        {
          if(this.selectOptionId.split(',')[i]!=sort)
          {
            newoption.push(this.selectOptionId.split(',')[i]);
          }
        }

        this.selectOptionId=newoption.sort().join(",");
      }
      else
      {
        this.selectOptionId=(this.selectOptionId+","+sort).split(",").sort().join(",");
      }
    }

    if(this.selectOptionId.indexOf(',')==0)
    {
      this.selectOptionId=this.selectOptionId.substring(1,this.selectOptionId.length)
    }
  }

  /**
   * 提交答案合法性判断
   * @returns {boolean}
   */
  isVaild():boolean
  {
    let flag=false;
    if(this.exerciseType=="10004"||this.exerciseType=="10006")
    {
      if(this.area_answer.trim()==""&&this.answer_type==0)
      {
        flag=false;
        //提示.按钮变灰显
        this.http.showToast("答案不能为空！","bottom");
      }
      else if(this.answerImages.trim()==""&&this.answer_type==1)
      {
        flag=false;
        //提示.按钮变灰显
        this.http.showToast("答案不能为空！","bottom");
      }
      else
      {
        flag=true;
      }
    }
    else if(this.exerciseType=="10001"||this.exerciseType=="10002"||this.exerciseType=="10008"||this.exerciseType=="10009") {
      if (this.selectOptionId == "") {
        //提示.按钮变灰显
        flag=false;
        this.http.showToast("答案不能为空！", "bottom");
      }
      else {
        flag=true;
      }
    }

    return flag;
  }

  /**
   * 倒计时计时器
   */
  counter()
  {
    if(this.classType=="60002")
    {
      if(this.exerciseStartTime == null || this.time > this.totalTime){
        this.flg = 1;
        this.counterText="未开始";
      }
      else if(this.time < 0)
      {
        //清空定时器
        clearInterval(this.interval);
        //清空录音记录
        this.flg=1;
        this.counterText="已结束";
      }
      else
      {
        if(this.flg==0)
        {

        }
        else
        {}
        //倒计时
        let t = this.timeStamp(this.time);
        let text = "倒计时 ";
        let day = t.split("#")[0].length == 2 ? t.split("#")[0] : "0" + t.split("#")[0];
        let hour = t.split("#")[1].length == 2 ? t.split("#")[1] : "0" + t.split("#")[1];
        let minute = t.split("#")[2].length == 2 ? t.split("#")[2] : "0" + t.split("#")[2];
        let second = t.split("#")[3].length == 2 ? t.split("#")[3] : "0" + t.split("#")[3];
        if(day != "00"){
          text += day + "天 ";
        }
        if(hour != "00"){
          text += hour + ":";
        }
        if(minute != "00"){
          text += minute + ":";
        }
        text += second;

        this.counterText=text;
      }
      this.time=this.time-1;
    }
    else if(this.classType=="60001"||this.classType=="60003")
    {
      this.totalTime=Date.parse(new Date().toString());

      if(this.flg==0)
      {
        if(this.start_answer!=1)
        {
          //??与源程序有出入
          this.counterText="不能答题";
        }
        else
        {
          this.counterText="答题中";
        }
      }
      else
      {
        this.counterText="不能答题";
      }

      clearInterval(this.interval);
    }
    else
    {
      this.flg=1;
      this.counterText="参数错误";
    }
  }

  // 入参：秒 出参：天#时#分#秒
  timeStamp(second_time):string{
    let timeCounter = "0#0#0#" + parseInt(second_time);
    if( parseInt(second_time) > 60){
      let second = parseInt(second_time) % 60;
      let min = parseInt(second_time/ 60+'');
      timeCounter = "0#0#" + min + "#" + second;
      if( min > 60 ){
        min = parseInt((second_time / 60) % 60+'');
        let hour = parseInt(parseInt(second_time / 60+'') /60+'');
        timeCounter = "0#" + hour + "#" + min + "#" + second;
        if( hour > 24 ){
          hour = parseInt(parseInt(second_time / 60+'') /60+'') % 24;
          let day = parseInt(parseInt(parseInt(second_time / 60+'') /60 +'') / 24+'');
          timeCounter = day + "#" + hour + "#" + min + "#" + second;
        }
      }
    }
    return timeCounter;
  }

  /**
   * 停用相应控件（提交按钮，输入框，选项等）
   * 停用提交按钮，录音按钮
   */
  disableControl()
  {}

  /**
   * 启用相应控件（提交按钮，输入框，选项等）
   * 启用提交按钮，录音按钮
   */
  enableControl()
  {
  }

  /**
   * 上传作答答案
   */
  uploadFile()
  {
    this.initImgSer();
    this.imgUpload.showPicActionSheet();
  }

  /**
   * 作答答案上传相关设置
   */
  initImgSer() {
    this.imgUpload.uploadApi = '/userstu/updateHeadPic.do';
    this.imgUpload.oldUserImage=this.oldAnswerImage;
    this.imgUpload.user_id=this.studentId;
    this.imgUpload.Type="Answer";
    if(this.answerImages=="")
    {
      this.imgUpload.maxUploadCount=this.maxImageCount;
    }
    else
    {
      this.imgUpload.maxUploadCount=this.maxImageCount-(this.answerImagesArray.length-1);
    }

    this.imgUpload.upload.success= (data)=> {
      //this.imgUpload.loading.dismiss();
      if(data["Code"]=="00000000")
      {
        this.answerImages=this.answerImages+data["ImgUrl"]+",";
        this.answerImagesArray=this.answerImages.split(',');
        this.showAnswerImages=this.showAnswerImages+this.http.filePath+data["ImgUrl"]+",";
        this.showAnswerImagesArray=this.showAnswerImages.split(",");

        if(this.answerImagesArray.length-1==this.maxImageCount)
        {
          this.canUpload=1;
        }
        else
        {
          this.canUpload=0;
        }
      }
      else
      {
        this.http.showToast(data["Message"],'bottom');
      }
    };

    this.imgUpload.upload.error= (err)=> {
      //this.imgUpload.loading.dismiss();
      this.http.showToast('上传失败','bottom');
    };
  }

  //移除答案图片
  clearAnswerImage(path) {
    if (path != null && path != "") {
      this.http.post('/userstu/delAnswerImage.do', {
        imgpath: path,
        Type: "Answer"
      }).subscribe(item => {
        this.showAnswerImagesArray.splice(this.answerImages.split(",").indexOf(path),1);
        this.showAnswerImages=this.showAnswerImagesArray.join(',');
        this.answerImagesArray.splice(this.answerImages.split(",").indexOf(path),1);
        this.answerImages=this.answerImagesArray.join(',');

        if(this.answerImagesArray.length-1==this.maxImageCount)
        {
          this.canUpload=1;
        }
        else
        {
          this.canUpload=0;
        }
      });
      /*    if(this.exerciseImagePath!=null&&this.exerciseImagePath!="")
          {
            this.http.post('/userstu/delAnswerImage.do',{
              imgpath:this.exerciseImagePath,
              Type:"Answer"
            }).subscribe(item=>{
              this.answerImage=null;
              this.exerciseImagePath=null;
            });
          }*/
    }
  }
}
